package com.jiangnan.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jiangnan.entity.Res
import com.jiangnan.entity.User
import com.jiangnan.repository.PaymentRepository
import com.jiangnan.repository.UserRepository
import kotlinx.coroutines.launch
import java.math.BigDecimal

class OverduePayViewModel : ViewModel() {
  private val payRepo = PaymentRepository()
  private val userRepo = UserRepository()

  private val _balance   = MutableLiveData<BigDecimal>()
  private val _overdue   = MutableLiveData<BigDecimal>()
  private val _error     = MutableLiveData<String>()

  val balance: LiveData<BigDecimal> = _balance
  val overdue: LiveData<BigDecimal> = _overdue
  val error: LiveData<String> = _error

  private val _toastMessage = MutableLiveData<String>()
  val toastMessage: LiveData<String> = _toastMessage

  fun loadUserInfo(userId: Long) {
    viewModelScope.launch {
      try {
        val res: Res<User> = userRepo.fetchUser(userId)
        if (res.code == 1 && res.data != null) {
          _balance.value = res.data.accountMoney
          _overdue.value = res.data.overduePay
          _toastMessage.postValue("加载成功")

        } else {
          _error.value = res.msg
        }
      } catch (e: Exception) {
        _error.value = e.message
        e.printStackTrace()
      }
    }
  }

  fun payOverdue(userId: Long, amount: BigDecimal) {
    viewModelScope.launch {
      try {
        val res = payRepo.payOverdue(userId, amount)
        if (res.code == 1) {
          // 重新拉取
          loadUserInfo(userId)
        } else {
          _error.value = res.msg
        }
      } catch (e: Exception) {
        _error.value = e.message
      }
    }
  }
}